package cn.well.cloud.base.wechat.api.impl;

import cn.well.cloud.base.util.HttpUtils;
import cn.well.cloud.base.wechat.api.AppAccessTokenAPI;
import cn.well.cloud.base.wechat.model.ApiAuthorizerInfoRequest;
import cn.well.cloud.base.wechat.model.Ticket;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class AppAccessToken implements AppAccessTokenAPI {

    // 获取（刷新）授权公众号或小程序的接口调用凭据（令牌）
    public static final String API_AUTHORIZER_TOKEN = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?";

    @Override
    public JSONObject getAuthorizerToken(String componentAccessToken, String componentAppid, String authorizerAppid, String authorizerRefreshToken) {
        String url = API_AUTHORIZER_TOKEN + "component_access_token=" + componentAccessToken;
        ApiAuthorizerInfoRequest apiAuthorizerInfoRequest = new ApiAuthorizerInfoRequest();
        apiAuthorizerInfoRequest.setComponent_appid(componentAppid);
        apiAuthorizerInfoRequest.setAuthorizer_appid(authorizerAppid);
        apiAuthorizerInfoRequest.setAuthorizer_refresh_token(authorizerRefreshToken);
        String infoRequestJson = JSONObject.toJSONString(apiAuthorizerInfoRequest);
        String result = null;
        try {
            result = HttpUtils.doPost(url,infoRequestJson,"plain");
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("返回信息："+result);
        JSONObject parseObject = JSONObject.parseObject(result);
        if (parseObject.containsKey("errcode")) {
            int errcode = parseObject.getIntValue("errcode");
            log.error("换取网页授权access_token失败，错误码：" + errcode);
            return null;
        } else {
            return parseObject;
        }
    }

    @Override
    public Ticket getTicket(String authorizerAccessToken) {
        // 访问微信服务器
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ authorizerAccessToken + "&type=jsapi";
        try {
            String result = HttpUtils.doGet(url);
            JSONObject json = JSONObject.parseObject(result);
            if (json != null&&json.containsKey("ticket")) {
                Ticket ticket = new Ticket();
                String jsapi_ticket = json.getString("ticket");
                ticket.setTicket(jsapi_ticket);
                ticket.setExpires_in(new Integer(json.getString("expires_in")));
                return ticket;
            }else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
